﻿using System;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using TissotWeb.GoogleMaps.Models;

namespace TissotWeb.GoogleMaps.Drivers
{
    public class GoogleMapDriver : ContentPartDriver<GoogleMapPart> {
        private readonly IOrchardServices _services;

        public GoogleMapDriver(IOrchardServices services) {
            _services = services;
        }

        protected override DriverResult Display(GoogleMapPart part, string displayType, dynamic shapeHelper) {
           ;
            return ContentShape("Parts_GoogleMap",
                () => shapeHelper.Parts_Map(ContentPart: part, ApiKey: _services.WorkContext.CurrentSite.As<GoogleMapSettingsPart>().GoogleMapApiKey));
        }

        //GET
        protected override DriverResult Editor(GoogleMapPart part, dynamic shapeHelper) {
            var vm = new GoogleMapPartViewModel {
                ApiKey = _services.WorkContext.CurrentSite.As<GoogleMapSettingsPart>().GoogleMapApiKey,
                Latitude = part.Latitude,
                Longitude = part.Longitude
            };
            return ContentShape("Parts_GoogleMap_Edit",
                () => shapeHelper.EditorTemplate(TemplateName: "Parts/GoogleMap", Model: vm, Prefix: Prefix));
        }

        //POST
        protected override DriverResult Editor(GoogleMapPart part, IUpdateModel updater, dynamic shapeHelper) {
            var vm = new GoogleMapPartViewModel();
            if (updater.TryUpdateModel(vm, Prefix, null, null)) {
                part.Latitude = vm.Latitude;
                part.Longitude = vm.Longitude;
            }

            return Editor(part, shapeHelper);
        }
    }
}
